package cn.blnp.net.flowable.boot.ext.manager;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.history.async.AsyncHistoryManager;
import org.flowable.engine.impl.history.async.HistoryJsonConstants;
import org.flowable.engine.runtime.ActivityInstance;
import org.springframework.stereotype.Component;

/**
 * <h3>自定义异步历史管理类</h3>
 *
 * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
 * @version 1.0
 * @since 2025/6/24 9:06
 */
@Slf4j
public class CustomAsyncHistoryManager extends AsyncHistoryManager {
    public CustomAsyncHistoryManager(ProcessEngineConfigurationImpl processEngineConfiguration) {
        super(processEngineConfiguration);
    }

    @Override
    public void updateHistoricActivityInstance(ActivityInstance activityInstance) {
        if (getHistoryConfigurationSettings().
                isHistoryEnabledForActivity(activityInstance)) {
            if (activityInstance.getExecutionId() != null) {
                ObjectNode data = processEngineConfiguration.getObjectMapper()
                        .createObjectNode();
                putIfNotNull(data, HistoryJsonConstants.PROCESS_INSTANCE_ID, activityInstance.getProcessInstanceId());
                putIfNotNull(data, HistoryJsonConstants.RUNTIME_ACTIVITY_INSTANCE_ID, activityInstance.getId());
                putIfNotNull(data, HistoryJsonConstants.TASK_ID, activityInstance.getTaskId());
                putIfNotNull(data, HistoryJsonConstants.ASSIGNEE, activityInstance.getAssignee());
                putIfNotNull(data, HistoryJsonConstants.CALLED_PROCESS_INSTANCE_ID, activityInstance.getCalledProcessInstanceId());
                getAsyncHistorySession().addHistoricData(getJobServiceConfiguration(),
                        HistoryJsonConstants.TYPE_UPDATE_HISTORIC_ACTIVITY_INSTANCE,
                        data);
            }
        }
    }

    /**
     * <p><b>用途:相关字段补充<b></p>
     * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
     * @since 9:11 2025/6/24
     * @params [node, key, value]
     * @param node
     * @param key
     * @param value
     * @return void
    **/
    public static void putIfNotNull(ObjectNode node, String key, String value) {
        if (StringUtils.isNotBlank(value)) {
            node.put(key, value);
        }
    }
}
